<template>
  <div class="login-container">
    <div class="login-box">
      <div class="tabs">
        <el-button @click="toggleForm('login')" :class="{ active: currentForm === 'login' }">登录</el-button>
        <el-button @click="toggleForm('register')" :class="{ active: currentForm === 'register' }">注册</el-button>
      </div>
      <div v-if="currentForm === 'login'" class="form-container">
        <h2>登录</h2>
        <el-form :model="loginForm" :rules="loginRules" ref="loginForm">
          <el-form-item prop="username">
            <el-input v-model="loginForm.username" placeholder="用户名"></el-input>
          </el-form-item>
          <el-form-item prop="password">
            <el-input type="password" v-model="loginForm.password" placeholder="密码"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" style="width: 100%; background: linear-gradient(to right, #6a11cb, #2575fc); border: none;" @click="submitLoginForm">登录</el-button>
          </el-form-item>
        </el-form>
      </div>
      <div v-if="currentForm === 'register'" class="form-container">
        <h2>注册</h2>
        <el-form :model="registerForm" :rules="registerRules" ref="registerForm">
          <el-form-item prop="account">
            <el-input v-model="registerForm.account" placeholder="账户"></el-input>
          </el-form-item>
          <el-form-item prop="password">
            <el-input type="password" v-model="registerForm.password" placeholder="密码"></el-input>
          </el-form-item>
          <el-form-item prop="checkPassword">
            <el-input type="password" v-model="registerForm.checkPassword" placeholder="再次确认密码"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" style="width: 100%; background: linear-gradient(to right, #6a11cb, #2575fc); border: none;" @click="submitRegisterForm">注册</el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>
  </div>
</template>

<script>
import axios from 'axios'
export default {
  
  data() {
    const validatePass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入密码'));
      } else {
        if (this.registerForm.checkPassword !== '') {
          this.$refs.registerForm.validateField('checkPassword');
        }
        callback();
      }
    };
    const validateCheckPass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'));
      } else if (value !== this.registerForm.password) {
        callback(new Error('两次输入密码不一致!'));
      } else {
        callback();
      }
    };

    return {
      currentForm: 'login',
      loginForm: {
        username: '',
        password: ''
      },
      registerForm: {
        account: '',
        password: '',
        checkPassword: ''
      },
      loginRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' }
        ]
      },
      registerRules: {
        account: [
          { required: true, message: '请输入账户', trigger: 'blur' }
        ],
        password: [
          { validator: validatePass, trigger: 'blur' }
        ],
        checkPassword: [
          { validator: validateCheckPass, trigger: 'blur' }
        ]
      }
    };
  },
  methods: {
    toggleForm(form) {
      this.currentForm = form;
    },
    submitLoginForm() {
      this.$refs.loginForm.validate((valid) => {
        if (valid) {
          const postData = {
            username: this.loginForm.username,
            password: this.loginForm.password
          };
          axios.post('http://127.0.0.1:5000/api/login', postData)
            .then(response => {
              if (response.status === 200) {
    alert('登录成功');
    sessionStorage.setItem('username', this.loginForm.username);
    localStorage.setItem('isNewLogin', 'true')
                        // 使用 Vue Router 跳转到首页或其他页面
                        this.$router.push("/home");
                        console.log(666)
              }
              
            })
            .catch(error => {
              let msg = error.response?.data?.error || '登录失败';
              alert(msg);
            });
         
        

        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    submitRegisterForm() {
      this.$refs.registerForm.validate((valid) => {
        if (valid) {
      
          // 在这里添加你的注册逻辑
          const postData = {
            username: this.registerForm.account,
            password: this.registerForm.password
          };
          axios.post('http://127.0.0.1:5000/api/register', postData)
          .then(response => {
            // 检查后端返回的状态和消息
            if (response.status === 201 && response.data.message) {
              alert('注册成功！');

              // 跳转到登录表单
              this.currentForm = 'login';

              // 自动填充用户名
              this.loginForm.username = this.registerForm.account;

              // 清空注册表单
              this.$refs.registerFormRef.resetFields();
            } else {
              alert('未知错误：' + response.data.error || '注册失败');
            }
          })
          .catch(error => {
            let msg = '注册失败，请检查输入信息';
            if (error.response && error.response.data && error.response.data.error) {
              msg = error.response.data.error;
            }
            alert(msg);
          });


        } else {
          console.log('error submit!!');
          return false;
        }
      });
    }
  }
}
</script>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background: linear-gradient(to right, #fbc2eb, #a6c1ee);
}

.login-box {
  width: 400px;
  padding: 30px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}

.tabs {
  display: flex;
  justify-content: center;
  margin-bottom: 20px;
}

.tabs .el-button {
  margin: 0 10px;
  background-color: transparent;
  border: 1px solid #dcdfe6;
  color: #606266;
  border-radius: 20px;
  padding: 8px 20px;
}

.tabs .el-button.active {
  background-color: #ebeef5;
  color: #409eff;
}

.form-container h2 {
  text-align: center;
  margin-bottom: 30px;
}

.el-form-item {
  margin-bottom: 20px;
}

.el-input__inner {
  border: none;
  border-bottom: 1px solid #dcdfe6;
  border-radius: 0;
  padding: 0;
}

.el-input__inner:focus {
  border-color: #409eff;
}
</style>